<?php
/*
 * @Autor: zs
 * @Date: 2021-05-26 09:12:32
 * @LastEditors: zs
 * @LastEditTime: 2021-05-26 16:03:50
 */
// 应用公共文件


use Symfony\Component\VarExporter\VarExporter;
use think\App;
use think\exception\HttpResponseException;
use think\facade\Config;
use think\facade\Db;
use think\facade\Event;
use think\Response;


/**
 * 下划线转驼峰
 * @param $str
 * @return null|string|string[]
 */
function lineToHump($str)
{
    $str = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
        return strtoupper($matches[2]);
    }, $str);
    return $str;
}

define('SHOPIFY','SHOPIFY');  //SHOPIFY
define('UPLOAD_FILE_DOMAIN_NAME','storage');
define('OPERATE_LOG', '/test/mnt/log/');
define('FILE_DOWNLOAD_DOMAIN_NAME','https://shopify.fan-zhou.com/');
//define('FILE_DOWNLOAD_DOMAIN_NAME','http://shopify.cn/');
/**
 * 驼峰转下划线
 * @param $str
 * @return null|string|string[]
 */
function humpToLine($str)
{
    $str = preg_replace_callback('/([A-Z]{1})/', function ($matches) {
        return '_' . strtolower($matches[0]);
    }, $str);
    return $str;
}

/**
 * @description: 成功
 * @param {*} $msg
 * @param {*} $data
 * @return {*}
 */
function success($msg = '', $data = [])
{
    # code...
    $data = [
        'code' => 200,
        'msg' => $msg,
        'time' => time(),
        'data' => $data,
    ];
    return json($data);
}
/**
 * @description: 失败
 * @param {*} $msg
 * @param {*} $data
 * @return {*}
 */
function error($msg = '', $data = [])
{
    $data = [
        'code' => 201,
        'msg' => $msg,
        'time' => time(),
        'data' => $data,
    ];
    return json($data);
}
/**
 * @description: 其他状态
 * @param {*} $msg
 * @param {*} $data
 * @return {*}
 */
function result($code = 0, $msg = '', $data = [])
{
    $data = [
        'code' => $code,
        'msg' => $msg,
        'time' => time(),
        'data' => $data,
    ];
    return json($data);
}
function addonresult($code = 0, $msg = '', $data = [], $type = 'json', array $header = [])
{
    $result = [
        'code' => $code,
        'msg' => $msg,
        'time' => time(),
        'data' => $data,
    ];
    $response = Response::create($result, $type)->header($header);
    throw new HttpResponseException($response);
}
/**
 * 获取真实ip
 */
function getRealIP()
{
    $forwarded = request()->header("x-forwarded-for");
    if ($forwarded) {
        $ip = explode(',', $forwarded)[0];
    } else {
        $ip = request()->ip();
    }
    return $ip;
}


function parseNodeStr($node)
{
    $array = explode('/', $node);
    foreach ($array as $key => $val) {
        if ($key == 0) {
            $val = explode('.', $val);
            foreach ($val as &$vo) {
                $vo = humpToLine(lcfirst($vo));
            }
            $val = implode('.', $val);
            $array[$key] = $val;
        }
    }
    $node = implode('/', $array);
    return $node;
}

/**
 * 控制器首字母边小写
 */
function parse_lower($controller)
{

    $val = explode('.', $controller);
    if (is_array($val)) {
        foreach ($val as &$vo) {
            $vo = humpToLine(lcfirst($vo));
        }
        $controller = implode('.', $val);
    }
    return $controller;
}

if (!function_exists('__url')) {

    /**
     * 构建URL地址
     * @param string $url
     * @param array $vars
     * @param bool $suffix
     * @param bool $domain
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        return url($url, $vars, $suffix, $domain)->build();
    }
}
if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     * @param $group
     * @param null $name
     * @return array|mixed
     */
    function sysconfig($group, $name = null)
    {
        $where = ['group' => $group];
        //$value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}");
        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
                $value = \app\admin\model\SystemConfig::where($where)->value('value');
                // Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600);
            } else {
                $value = \app\admin\model\SystemConfig::where($where)->column('value', 'name');
                // Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600);
            }
        }
        return $value;
    }
}

/**
 * api发起POST请求
 * @param  string  $func     [请求api方法]
 * @param  string  $data     [请求api数据]
 */
function api_post(string $func, $data = [], $header = [])
{
    $url = config('app.api') . $func;
    $output = curl($url, $data, $header);
    return json_decode($output, true);
}

/**
 * CURL请求函数:支持POST及基本header头信息定义
 * @param  string  $api_url      [请求远程链接]
 * @param  array   $post_data    [请求远程数据]
 * @param  array   $header       [头信息数组]
 */
function curl(string $api_url, $post_data = [], $header = [])
{
    /**初始化CURL句柄**/
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    /**配置返回信息**/
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //获取的信息以文件流的形式返回，不直接输出
    curl_setopt($ch, CURLOPT_HEADER, 0); //不返回header部分
    /**配置超时**/
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //连接前等待时间,0不等待
    curl_setopt($ch, CURLOPT_TIMEOUT, 60); //连接后等待时间,0不等待。如下载mp3
    /**配置页面重定向**/
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //跟踪爬取重定向页面
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10); //指定最多的HTTP重定向的数量
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    /**配置Header、请求头、协议信息**/
    $header[] = "CLIENT-IP:" . request()->ip();
    $header[] = "X-FORWARDED-FOR:" . request()->ip();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_ENCODING, ""); //Accept-Encoding编码，支持"identity"/"deflate"/"gzip",空支持所有编码
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Baiduspider/2.0; +" . request()->domain() . request()->domain() . ")");
    //模拟浏览器头信息
    curl_setopt($ch, CURLOPT_REFERER, request()->domain()); //伪造来源地址
    /**配置POST请求**/
    if ($post_data && is_array($post_data)) {
        curl_setopt($ch, CURLOPT_POST, 1); //支持post提交数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
    }
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //禁止 cURL 验证对等证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //是否检测服务器的域名与证书上的是否一致
    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        // 捕抓异常
        return ['status' => 'error', 'message' => curl_error($ch)];
    } else {
        // 正常返回
        curl_close($ch);
        return $data;
    }
}
/**
 * 返回后台跟目录
 */
function get_back_addons_path()
{

    $back_addons_path = root_path() . "addons";
    // 如果插件目录不存在则创建
    if (!is_dir($back_addons_path)) {
        @mkdir($back_addons_path, 0755, true);
    }
    return $back_addons_path;
}
/**
 * 获取插件所有的配置
 */
function get_addons_all_config($name)
{
    $addon = get_addons_instance($name);
    if (!$addon) {
        return [];
    }
    $config = $addon->getConfig(true);
    return $config;
}
/**
 * 获取插件配置 数组格式
 */
function get_addons_config_format($name)
{
    $configf = [];
    $config = get_addons_all_config($name);
    foreach ($config as $k => $v) {
        $configf[$v['name']] = $v['value'];
    }
    return $configf;
}

function full_url(string $relativeUrl = '', bool $domain = true, string $default = ''): string
{
    // 存储/上传资料配置
    Event::trigger('uploadConfigInit', App::getInstance());

    $cdnUrl = Config::get('admin.cdn_url');
    if (!$cdnUrl) $cdnUrl = request()->upload['cdn'] ?? request()->domain();
    if ($domain === true) {
        $domain = $cdnUrl;
    } elseif ($domain === false) {
        $domain = '';
    }

    $relativeUrl = $relativeUrl ?: $default;
    if (!$relativeUrl) return $domain;

    $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
    if (preg_match('/^http(s)?:\/\//', $relativeUrl) || preg_match($regex, $relativeUrl) || $domain === false) {
        return $relativeUrl;
    }
    return $domain . $relativeUrl;
}




/**
 * 设置插件配置
 */
function set_addons_config($name, $config)
{
    $file = get_back_addons_path() . DIRECTORY_SEPARATOR . $name . DIRECTORY_SEPARATOR . "config.php";
    if (!is_file($file)) {
        throw new \Exception("配置文件不存在");
    }
    if (!is_writable($file)) {
        throw new \Exception("配置文件无法写入");
    }
    $res = file_put_contents($file, "<?php\n\n" . "return " . VarExporter::export($config) . ";\n", LOCK_EX);
    if (!$res) {
        throw new \Exception("配置修改失败");
    }
    return true;
}


if (!function_exists('table')) {
    function table($table)
    {
        return Db::name($table);
    }
}

if (!function_exists('excelTime')) {
    function excelTime($days, $time = false)
    {
        if (is_numeric($days)) {
            //based on 1900-1-1
            $jd = GregorianToJD(1, 1, 1970);
            $gregorian = JDToGregorian($jd + intval($days) - 25569);
            $myDate = explode('/', $gregorian);
            $myDateStr = str_pad($myDate[2], 4, '0', STR_PAD_LEFT)
                . "-" . str_pad($myDate[0], 2, '0', STR_PAD_LEFT)
                . "-" . str_pad($myDate[1], 2, '0', STR_PAD_LEFT)
                . ($time ? " 00:00:00" : '');
            return $myDateStr;
        }
        return $days;
    }
}

function p($info = [])
{
     print_r($info);
}

function isMobiles($mobile)
{
    if (!is_numeric($mobile) || strlen($mobile) != 11) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0-8]{1}\d{8}$|^18[\d]{9}$|^19[\d]{9}$#', $mobile) ? true : false;
}

function DefaultResponse($code, $success = false, $msg = "加载错误", $data = null)
{
    $obj = new stdClass();
    $obj->code = $code;
    $obj->success = $success;
    $obj->msg = $msg;
    $obj->data = $data;
    return $obj;
}

function getVcode($size = 6)
{
    $code = '';
    for ($i = 1; $i <= $size; $i++) {
        $code .= chr(rand(97, 122));
    }
    return $code;
}

function objectToArray($object)
{
    return $object ? json_decode(json_encode($object), true) : [];
}

/**
 * 生成token
 * @return string
 */
function tokens()
{
    $str = md5(uniqid(md5(microtime(true)), true));  //生成一个不会重复的字符串
    $str = sha1($str);  //加密
    return $str;
}

function getLevel($list = [])
{
    $arr = [];
    foreach ($list as $key => $value) {
        $arr[] = [
            'key'   => $key,
            'value' => $value,
        ];
    }
    return $arr;
}

function listToTree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0) {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

function get_shopify_spu($string,$num){
    $parts = explode('+', $string);
    $type  = count($parts);
    //获取spu
    $spu_info   = explode('-', $parts[0]);
    $spu        = $spu_info[0];
    $sizes_info = explode('-', $parts[$type-1]);
    $sizes      = $sizes_info['1'];
    switch($type){
        case 1:
             //查看string 尾部是否有数字
            if (preg_match('/.*-(\d+)$/', $string, $matches)) {
                return  $string;
             }else{
                return  $num >1 ? $string.'-'.$num : $string;
            }
        case 2:
            preg_match('/-([a-zA-Z]+)/', $parts[0], $matches_color0);
            $color0 = $matches_color0[1];
            preg_match('/^([a-zA-Z]+)/',    $parts[1], $matches_color1);
            $color1 = $matches_color1[1];
            preg_match('/-([a-zA-Z0-9]+)/', $parts[1], $matches_size);
            $size  = $matches_size[1];
            if($num >1){
                return $spu.'-'.$color0.'-'.$size.'-'.$num.','.$spu.'-'.$color1.'-'.$size.'-'.$num;
            }else{
                return $spu.'-'.$color0.'-'.$size.','.$spu.'-'.$color1.'-'.$size;
            }
        case 3:
            preg_match('/-([a-zA-Z]+)/', $parts[0], $matches_color0);
            $color0 = $matches_color0[1];
            $color1 = $parts[1];
            $parts2 = explode("-", $parts[2]);
            $color2 = $parts2[0];
            $size   = $parts2[1];
            if($num >1){
                return $spu.'-'.$color0.'-'.$size.'-'.$num.','.$spu.'-'.$color1.'-'.$size.'-'.$num.','.$spu.'-'.$color2.'-'.$size.'-'.$num;
            }else{
                return $spu.'-'.$color0.'-'.$size.','.$spu.'-'.$color1.'-'.$size.','.$spu.'-'.$color2.'-'.$size;
            }
        default:
            $list = [];
            foreach($parts as $k=>$v){
                if($k==0){
                    $list[$k] = $spu.'-'.$spu_info[1].'-'.$sizes;
                }elseif($k==$type-1){
                    $list[$k] = $spu.'-'.$parts[$k];
                }else{
                    $list[$k] = $spu.'-'.$parts[$k].'-'.$sizes;
                }
            }
            return  $list ? implode(',',$list) : '';
    }
}

function get_product_sku($string,$num){
    $parts = explode('+', $string);
    $type  = count($parts);
    //获取spu
    $spu_info   = explode('-', $parts[0]);
    $spu        = $spu_info[0];

    switch($type){
        case 1:
            //查看string 尾部是否有数字
            if (preg_match('/.*-(\d+)$/', $string, $matches)) {
                return preg_replace('/(-\d+)$/', '', $string);
            }else{
                return  $string;
            }
        case 2:
            preg_match('/-([a-zA-Z]+)/', $parts[0], $matches_color0);
            $color0 = $matches_color0[1];
            preg_match('/^([a-zA-Z]+)/',    $parts[1], $matches_color1);
            $color1 = $matches_color1[1];
            preg_match('/-([a-zA-Z0-9]+)/', $parts[1], $matches_size);
            $size  = $matches_size[1];
            return $spu.'-'.$color0.'-'.$size.','.$spu.'-'.$color1.'-'.$size;
        case 3:
            preg_match('/-([a-zA-Z]+)/', $parts[0], $matches_color0);
            $color0 = $matches_color0[1];
            $color1 = $parts[1];
            $parts2 = explode("-", $parts[2]);
            $color2 = $parts2[0];
            $size   = $parts2[1];
            return $spu.'-'.$color0.'-'.$size.','.$spu.'-'.$color1.'-'.$size.','.$spu.'-'.$color2.'-'.$size;

        case 4:
            preg_match('/-([a-zA-Z]+)/', $parts[0], $matches_color0);
            $color0 = $matches_color0[1];
            $color1 = $parts[1];
            $color2 = $parts[2];
            $parts3 = explode("-", $parts[3]);
            $color3 = $parts3[0];
            $size   = $parts3[1];
            return $spu.'-'.$color0.'-'.$size.','.$spu.'-'.$color1.'-'.$size.','.$spu.'-'.$color2.'-'.$size.','.$spu.'-'.$color3.'-'.$size;
      }
}

function get_real_time($dateString){
    $dateTime = new DateTime($dateString);
   return $dateTime->format('Y-m-d H:i:s');
}

function  get_utc_time($originalTimeStr){
    // 创建 DateTime 对象，自动处理时区
    $dateTime = new DateTime($originalTimeStr);
    $dateTime->setTimezone(new DateTimeZone('UTC'));
    $convertedTimeStr = $dateTime->format('Y-m-d H:i:s');
    return  $convertedTimeStr;
}



   function get_seller_sku($order = '') {
    //获取品牌
    $patter = '/^([^\-]+)/';
    preg_match($patter, $order, $matche);
    $first = $matche[1];
    //获取sku
    $pattern = '/((?:[-+]\w+)+)/';
    preg_match($pattern, $order, $matches);
    if ($matches) {
        $info = explode('-', trim($matches[1], '+'));
        if(isset($info[0]))  unset($info[0]);
        $color_arr = explode('+',$info[1]);
        $last      = end($info);
        if($last=='XL/2XL'){
            $last = 'XL';
        }
        if($last=='3XL/4XL'){
            $last = '3XL';
        }

        if($last=='4XL/5XL'){
            $last = '4XL';
        }

        if($last=='5XL/6XL'){
            $last = '5XL';
        }

        if($last=='6XL/7XL'){
            $last = '6XL';
        }

        if($last=='XS/S'){
            $last = 'S';
        }
        if($last=='M/L'){
            $last = 'M';
        }

        $letterArr = ['M','S','2XL','XXL','XL','3XL','4XL','5XL','6XL','7XL','8XL','S/M','L/XL'];
        $num = !in_array($last,$letterArr) && in_array($last,[1,2,3,4,5,6,7,8]) ? $last * count($color_arr) : count($color_arr);
        $second_arr= [];
        if(!in_array($last,$letterArr) && in_array($last,[1,2,3,4,5,6,7,8])){
            //取第二个-号的数据;
            $express ='/(?:[^-]*-){2}([^-\s]+)/'; // 匹配以 - 开头的单词字符（包括字母、数字和下划线）
            preg_match($express, $order, $second_arr);
            $size = $second_arr[1]??'';
        }else{
            $size = $last;
        }

        $single_num = !in_array($last,$letterArr) && in_array($last,[1,2,3,4,5,6,7,8]) ? $last : 1;
        if($num<=1){
            $arr = [
                'lineNo'    => 2,
                'sku'       => $order,
                'qtyOrdered'=> $single_num
            ];
        }else{
            foreach($color_arr as $k=>$v){
                $arr[] = [
                    'lineNo'          =>$k+3,
                    'sku'             =>$size ? $first.'-'.$v.'-'.$size: $first.'-'.$v,
                    'qtyOrdered'      =>$single_num,
                ];
            }
        }
        return $arr;
    } else {
        return [];
    }

}

    //过滤表情包
   function filterEmoji($str)
   {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
    
        return trim($str);
    }

    //美国夏令时区
    function timezone()
    {
        return 15*3600;
    }

    //广告转点时间
    function updatetime_automatic()
    {
        return date('Y-m-d', time() - timezone());
    }

   function updatetime_automatic_format()
   {
       $dateString =  date('Y-m-d', time() - timezone());
       $dateTime   = new DateTime($dateString);
       $dateTime->setTime(0, 0, 0);
       return $dateTime->format('Y-m-d H:i:s');

   }


function updatetime_automatic_date($dateString)
{
    if(!$dateString)  return  '';
    $dateString = str_replace(' ', '', $dateString);
    $dateTime   = new DateTime($dateString);
    return  $dateTime->format('Y-m-d H:i');

}


function  get_unique_order($data){
    $result = [];
    foreach ($data as $item) {
        $orderId = $item['order_id'];

        // 处理 SKU 去掉最后的 /<size>
        $sku = $item['sku'];
        $lastSlashPosition = strpos($sku, '/');
        if ($lastSlashPosition !== false) {
            $sku = substr($sku, 0, $lastSlashPosition); // 保留 / 之前的部分
        }
        $item['sku'] = $sku;

        if (!isset($result[$orderId])) {
            // 如果这个order_id还没有被设置，先初始化为一个空数组
            $result[$orderId] = [];
        }
        // 将当前的 item 添加到这个 order_id 的数组中
        $result[$orderId][] = $item;
    }
    return  $result;
}



function  get_unique_supply($data){
    $result = [];
    foreach ($data as $item) {
        $orderId = $item['supply_id'];

        // 处理 SKU 去掉最后的 /<size>
        $sku = $item['seller_sku'];
        $lastSlashPosition = strpos($sku, '/');
        if ($lastSlashPosition !== false) {
            $sku = substr($sku, 0, $lastSlashPosition); // 保留 / 之前的部分
        }
        $item['seller_sku'] = $sku;

        if (!isset($result[$orderId])) {
            // 如果这个order_id还没有被设置，先初始化为一个空数组
            $result[$orderId] = [];
        }
        // 将当前的 item 添加到这个 order_id 的数组中
        $result[$orderId][] = $item;
    }
    return  $result;
}









function  get_package_id(){
    return 'XMH7LMA'.random_int(1000, 99999);
}



function getRes($number){
    return number_format($number, 2,".","");
}

function getResFour($number){
    return number_format($number, 4,".","");
}

function getInNumber(){
    return 'IN'.random_int(10000, 999999);
}

function getPurchaseNumber(){
    return 'POH7LM'.random_int(10000, 999999);
}




function arraySortByKeys($array, $keys)
{
    $value = [];
    foreach($keys as $key) {
        if (isset($array[$key])) {
            $value[$key] = $array[$key];
        }
    }
    return $value;
}

function convertToTimeFormat($decimalDegrees) {
    // 获取整数部分和小数部分
    $degrees = floor($decimalDegrees);
    $decimalMinutes = ($decimalDegrees - $degrees) * 60;
    $minutes = floor($decimalMinutes);
    $seconds = ($decimalMinutes - $minutes) * 60;

    // 格式化时间为 HH:MM:SS
    $timeFormat = sprintf('%02d:%02d:%02d', 0, $minutes, round($seconds));

    return $timeFormat;
}


function generateRandomString($length = 43) {
    return bin2hex(random_bytes($length / 2));
}
// Base64 URL 编码的函数
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function paginateArray($array, $currentPage, $itemsPerPage) {
    // 计算总项数
    $totalItems = count($array);

    // 计算总页数
    $totalPages = ceil($totalItems / $itemsPerPage);

    // 确保当前页数在合理范围内
    if ($currentPage < 1) {
        $currentPage = 1;
    } elseif ($currentPage > $totalPages) {
        $currentPage = $totalPages;
    }

    // 计算起始索引
    $startIndex = ($currentPage - 1) * $itemsPerPage;

    // 获取当前页数据
    $pagedArray = array_slice($array, $startIndex, $itemsPerPage);

    return [
        'current_page' => $currentPage,
        'total_pages'  => $totalPages,
        'data'         => $pagedArray,
        'total'        => $totalItems
    ];
}


function urladdparam($url,$arr=[]){
    if(empty($arr)){
        return $url;
    }
    $arr1=[];
    foreach($arr as $key=>$val){
        $arr1[]=$key."=".$val;
    }
    return rtrim($url,'/').'?'.implode('&',$arr1);
}

function getDateTime($timeString){
    $dateTime  = new DateTime($timeString);
    return $dateTime->format('Y-m-d H:i:s');
}

function getOfferIdFromUrl($url) {
    // 正则匹配 URL 中的 offer/数字部分
    preg_match('/\/offer\/(\d+)(\.html|\/)?/', $url, $matches);
    return $matches[1] ?? null;
}






